-module(get_access_token).
-author("hpj").

-import(proplists, [get_value/2, get_value/3]).

-include("emqttd.hrl").

-include("mysql.hrl").

%% API
-export([handle/1]).

%% register user
handle(Params) ->
  	Appkey = get_value(<<"appkey">>,Params),
	SecretKey = get_value(<<"secretkey">>,Params),
	UserId = get_value(<<"uid">>,Params),
	Echostr = tools:generate_rand(16),
	case mnesia:dirty_match_object(user_info,#user_info{platform_type = 8,id = UserId,_ ='_'}) of  
		[] ->
			{ok, [{<<"code">>,5},{<<"message">>,<<"this uid not set config">>}]};
		_ ->
			case mnesia:dirty_match_object(user_info,#user_info{appkey = Appkey,id = UserId,_ ='_'}) of 
				[] ->
					{ok, [{<<"code">>,2},{<<"message">>,<<"uid not belong this appkey">>}]};
				_ ->
					case mysql_utils:select(?IM_POOL,business,"secretkey",[{appkey,"=",Appkey,"and"},{secretkey,"=",SecretKey}]) of 
						[] ->
							{ok, [{<<"code">>,2},{<<"message">>,<<"appkey or secretkey error,please check it">>}]};
						_ ->
							case mnesia:dirty_read(ham_user_token,UserId) of 
								[] ->
									AccessToken = list_to_binary(md5_string:md5_hex(tools:selection(binary_to_list(Appkey)++binary_to_list(SecretKey)++Echostr))),
									TokenRecord = #ham_user_token{user_id = UserId,token = AccessToken,num = 1},
									mnesia:dirty_write(ham_user_token,TokenRecord),
									gen_server:cast(whereis(token_check_interval),{token_clear,TokenRecord}),
									{ok, [{<<"code">>,0},{<<"access_token">>,AccessToken},{<<"expires_in">>,7200}]};
								[Record] ->
%									Num = Record#ham_user_token.num,
%									case Num < 500 of 
%										true ->
											AccessToken = list_to_binary(md5_string:md5_hex(tools:selection(binary_to_list(Appkey)++binary_to_list(SecretKey)++Echostr))),
											TokenRecord = Record#ham_user_token{ user_id = UserId,token = AccessToken },
											mnesia:dirty_write(ham_user_token,TokenRecord),
											gen_server:cast(whereis(token_check_interval),{token_more_clear,TokenRecord}),
											{ok, [{<<"code">>,0},{<<"access_token">>,AccessToken},{<<"expires_in">>,7200}]}
%										false ->
%											{ok,[{<<"code">>,4}]}
%									end	
							end			    
					end			
			end
	end.			
	
